package com.media.publish.utils;


import android.content.Context;
import android.text.TextUtils;

import com.baselibrary.MessageBus;
import com.baselibrary.utils.BitmapUtils;
import com.baselibrary.utils.ContextUtils;
import com.baselibrary.utils.EventBusUtils;
import com.baselibrary.utils.FileUtils;
import com.baselibrary.utils.HKLogUtils;
import com.baselibrary.utils.MediaFileUtils;
import com.baselibrary.utils.StorageUtils;
import com.okhttp.callbacks.StringCallback;
import com.okhttp.utils.APIUrls;
import com.okhttp.utils.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;
import com.media.publish.bean.MultiImageResp;
import com.media.publish.upload.TXUGCPublish;
import com.media.publish.upload.TXUGCPublishTypeDef;

/**
 * @author:hanke 2022/7/5
 * desc:
 */
public class UploadMediaUtils {
    public static void uploadVideo(String videoPath, UploadVideoListener uploadVideoListener) {
        OkHttpUtils.getInstance()
                .post()
                .url(APIUrls.URL_createSecurityTokenTx)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject json = new JSONObject(response);
                            boolean success = json.getBoolean("success");
                            if (success) {
                                JSONObject data = json.optJSONObject("data");
                                String signature = data.optString("signature");
                                String returnUrl = data.optString("returnUrl");
                                uploadVideoToTencent(signature, returnUrl, videoPath, uploadVideoListener);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public static void uploadFile(Context context, String filePath, UploadFileListener uploadFileListener) {
        String mCoverPath = MediaFileUtils.createVideoThumbnailFile(context, new File(filePath)).getPath();
        String filename = mCoverPath.substring(mCoverPath.lastIndexOf("/") + 1);
        OkHttpUtils.post()
                .addFile("file", filename, new File(mCoverPath))
                .url(APIUrls.URL_UPLOAD_FILES)
                .build()
                .execute(new StringCallback() {

                    @Override
                    public void onBefore(Request request, int id) {
                    }

                    @Override
                    public void onAfter(int id) {
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_total_status, "上传失败");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject object = new JSONObject(response);
                            if (uploadFileListener != null) {
                                uploadFileListener.onComplete(object.getString("ok"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                    }
                });
    }

    public static void uploadImages(ArrayList<String> imagesPaths, UploadImageListener uploadImageListener) {
        ArrayList<String> mCompressList = new ArrayList<>();
        for (int i = 0; i < imagesPaths.size(); i++) {
            File fromFie = new File(imagesPaths.get(i));
            String newImgPath = StorageUtils.getAppPath(StorageUtils.TEMP_PATH) + "/" + System.currentTimeMillis() + "_" + i + FileUtils.getMediaSuffixName(fromFie);
            File mTagFile = new File(newImgPath);
            BitmapUtils.qualityCompress(ContextUtils.getCurApplication(), fromFie, mTagFile);
            mCompressList.add(mTagFile.getAbsolutePath());
        }
        OkhttpUtils.getInstance(ContextUtils.getCurApplication()).upLoadMultiImage(Urls.URL_MULTI_IMAGE, mCompressList, MultiImageResp.class, new BaseCallback<MultiImageResp>() {

            @Override
            public void onFailure(Call call, IOException e) {
                HKLogUtils.e("发布上传图片报错："+e.toString());
                if (uploadImageListener != null) {
                    uploadImageListener.onComplete(null);
                }
            }

            @Override
            public void onResponse(Call call, MultiImageResp questionRespT) throws IOException {
                if (uploadImageListener != null) {
                    uploadImageListener.onComplete(questionRespT);
                }
            }
        });
    }

    public static void uploadVideoToTencent(String signature, final String returnUrl, String videoPath, UploadVideoListener uploadListener) {
        TXUGCPublish mVideoPublish = new TXUGCPublish(ContextUtils.getCurApplication(), "independence_android");
        mVideoPublish.setListener(new TXUGCPublishTypeDef.ITXVideoPublishListener() {
            @Override
            public void onPublishProgress(long uploadBytes, long totalBytes) {
                if (uploadListener != null) {
                    uploadListener.onProgress(uploadBytes, totalBytes);
                }
            }

            @Override
            public void onPublishComplete(TXUGCPublishTypeDef.TXPublishResult result) {
                if (!TextUtils.isEmpty(result.videoId)) {
                    String videoUrl = returnUrl + result.videoId;//视频URL
                    if (uploadListener != null) {
                        uploadListener.onComplete(videoUrl,result.coverURL);
                    }
                }
            }
        });

        TXUGCPublishTypeDef.TXPublishParam param = new TXUGCPublishTypeDef.TXPublishParam();
        param.signature = signature;
        param.videoPath = videoPath;
        param.coverPath=  MediaFileUtils.createVideoThumbnailFile(ContextUtils.getCurApplication(), new File(videoPath)).getPath();
        mVideoPublish.publishVideo(param);
    }

    public interface UploadVideoListener {
        void onProgress(long uploadBytes, long totalBytes);

        void onComplete(String videoUrl,String videoCoverUrl);
    }

    public interface UploadImageListener {

        void onComplete(MultiImageResp questionRespT);
    }

    public interface UploadFileListener {

        void onComplete(String fileUrl);
    }

}
